package top.ijiujiu.component;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;
import top.ijiujiu.util.ResultUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 已登录但无权限请求资源处理
 *
 * @Author 神秘的黄瓜
 * @Version 1.0
 * @Date 2020-06-22 15:26
 */
@Component
public class AccessDeniedHandlerImpl implements AccessDeniedHandler {

    private final static Logger LOGGER = LoggerFactory.getLogger(AccessDeniedHandlerImpl.class);

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    @SuppressWarnings("deprecation")
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException, ServletException {
        LOGGER.error("没有访问权限~~~~~~");
        ResultUtil<Boolean> result = new ResultUtil<>();
        result.failed(HttpStatus.UNAUTHORIZED.value(),"没有访问权限~~~~~~", false);
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        response.getWriter().write(objectMapper.writeValueAsString(result));
    }
}
